import datetime
from flask_login import UserMixin
from sqlalchemy import DateTime, Numeric
from werkzeug.security import generate_password_hash, check_password_hash
from applications.exts import db


class WxUser(db.Model, UserMixin):
    __tablename__ = 'wx_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
    username = db.Column(db.String(20), comment='小程序用户名')
    openid = db.Column(db.String(60), unique=True, comment='小程序用户openid')
    avatar = db.Column(db.String(255), comment='头像', default="/static/admin/admin/images/avatar.jpg")
    remark = db.Column(db.String(255), comment='备注')
    phone = db.Column(db.String(11), comment='手机号')
    password_hash = db.Column(db.String(128), comment='哈希密码')
    enable = db.Column(db.Integer, default=1, comment='启用')
    level=db.Column(db.Integer,default=0,comment='用户等级')
    integral=db.Column(db.Integer,default=0,comment='用户积分')
    create_at = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
    update_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def validate_password(self, password):
        return check_password_hash(self.password_hash, password)

    def to_dict(self):
        res = {}
        for col in self.__table__.columns:
            if isinstance(col.type, DateTime):  # 判断类型是否为DateTime
                if not getattr(self, col.name):  # 判断实例中该字段是否有值
                    value = ""
                else:  # 进行格式转换
                    value = getattr(self, col.name).strftime("%Y-%m-%d %H:%M:%S")
            elif isinstance(col.type, Numeric):  # 判断类型是否为Numeric
                value = float(getattr(self, col.name))  # 进行格式转换
            else:  # 剩余的直接取值
                value = getattr(self, col.name)
            res[col.name] = value
        return res
